package com.maserb.monitor.repository.schoolStudent;

import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.entity.schoolStudent.StudentAchieveEntity;
import com.maserb.monitor.model.StudentAchieveModel;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository
public interface StudentAchieveRepository extends JpaSpecificationExecutor<StudentAchieveEntity>
        , PagingAndSortingRepository<StudentAchieveEntity, String> {

    @Query(value = "select avg(avgScore) from StudentAchieveEntity where student.id=?1 and clazzId=?2 and avgScore is not null")
    Double queryAvgScoreByStudent(String studentId, String clazzId);

    @Query(value = "select r from StudentAchieveEntity r  where r.student=?1 and r.createTime>?2 and r.createTime<?3 order by r.createTime")
    List<StudentAchieveEntity> findByStudent(SchoolStudentEntity student,Date startTime, Date endTime);

    @Query(value = "select avg (r.avgScore) from StudentAchieveEntity r left join r.student s where s.orgId=?1 and r.createTime>?2 and r.createTime<?3 and r.avgScore is not null group by r.student")
    Double[] findAchieveByClazz(String clazzId, Date startTime, Date endTime);

    @Query(value = "select avg (r.score) from StudentScoreEntity r left join StudentAchieveEntity ac on r.achieve = ac left join ac.student s where s.orgId=?1 and ac.createTime>?2 and ac.createTime<?3 and r.subject = ?4 and ac.avgScore is not null group by ac.student")
    Double[] findAchieveByClazzAndCode(String clazzId, Date startTime, Date endTime, SysCode code);

    @Query(value = "select avg (r.score) from StudentScoreEntity r left join StudentAchieveEntity ac on r.achieve = ac and ac.term = ?2 left join ac.student s where s.orgId=?1  and r.subject = ?3 and ac.avgScore is not null ")
    Double findAchieveByClazzAndCodeAndAchieve(String clazzId, String term,SysCode code);

    StudentAchieveEntity findFirstByStudentAndTermId(SchoolStudentEntity student, String termId);

    @Query(value = "select r from StudentAchieveEntity r  where r.student=?1 order by r.createTime desc")
    List<StudentAchieveEntity> findByStudentByCreateTime(SchoolStudentEntity student);

    @Query(value = "select r from StudentAchieveEntity r left join r.student s where s.orgId=?1 and r.term =?2 order by r.totalScore DESC ")
    List<StudentAchieveEntity> findAchieveByClazzOrderByTotalScoreDesc(String clazzId,String term);
}